/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.yongw.MouseMove;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import javafx.application.Platform;
import javafx.scene.control.TextArea;
import javafx.scene.text.Text;
import static cn.yongw.MouseMove.ReceiveDataUtil.receiveData;
/**
 * wifi服务器
 * @author 张永伟
 */
public class WifiJavaServer extends JavaServer{   
    Socket socket;
    DataInputStream io;
    private TextArea ta;
    private Text tvMsg;
    private String hostName;
    Format format;    
    boolean isRunning = true;
    ServerSocket serverSocket;
    
    /**
     * @param ta 展示通知的窗口
     * @param tvMsg 展示主机ip的窗口
     */   
    public WifiJavaServer(TextArea ta, Text tvMsg) throws HostNullException {
        this.ta = ta;
        this.tvMsg = tvMsg;
        format = new SimpleDateFormat("YYYY年yy月dd日HH:mm:ss.SSS");        
        Enumeration<NetworkInterface>networkInterfaces;
        try {
            networkInterfaces = NetworkInterface.getNetworkInterfaces();
             NetworkInterface networkInterface;
            Enumeration<InetAddress> inetAddress;
            InetAddress inetAddres;
            while(hostName== null && networkInterfaces.hasMoreElements()){
                networkInterface = networkInterfaces.nextElement();
                inetAddress = networkInterface.getInetAddresses();
                while(hostName== null && inetAddress.hasMoreElements()){
                    inetAddres = inetAddress.nextElement();
                    if(inetAddress != null && inetAddres instanceof Inet4Address){
                        if(networkInterface.getName().contains("wl") || networkInterface.getName().contains("WL") ||
                                networkInterface.getDisplayName().contains("Microsoft Hosted Network"))
                            hostName = inetAddres.getHostAddress();
                    }                    
                }
            }
            if(hostName == null)
                throw new HostNullException("电脑未连接至无线网络");   
        } catch (SocketException ex) {
            ex.printStackTrace();
        }     
        isRunning=true;
    }    

    @Override
    public void run(){
        try{
            if(hostName != null){
                tvMsg.setText("本机IP为:" + hostName);                    
                serverSocket = new ServerSocket(8000);
                Platform.runLater(() -> ta.appendText(format.format(new Date()) +  " -> 服务于端口8000启动\n"));
                
                while(isRunning){
                    System.out.println("server start listerening………");
                    Platform.runLater(() -> ta.appendText(format.format(new Date()) + "-> 无线鼠标wifi电脑端已启动,等待手机端连接\n"));
                    socket = serverSocket.accept();  
                    io = new DataInputStream(socket.getInputStream());
                    byte[] buffer = new byte[1024];                    
                    io.read(buffer);
                    String command = new String(buffer).trim();//一定要加trim，要不然不一样
                    while("search".equals(command)){//接受到连接命令跳出来
                        buffer = new byte[1024];
                        socket.close();
                        socket = serverSocket.accept();
                        io = new DataInputStream(socket.getInputStream());
                        io.read(buffer);
                        command = new String(buffer).trim();                       
                    }
                    
                    System.out.println("receive connect");
                    Platform.runLater(() -> ta.appendText(format.format(new Date()) +
                            "-> 连接成功,客户端IP为:"+socket.getInetAddress().getHostAddress()+",可以开始操作\n"));
                    
                    System.out.println("start readdata……");
                    receiveData(io, ta);             
                    System.out.println("end receive, wait for another connect");
                    
                    Platform.runLater(() -> ta.appendText(format.format(new Date()) + "-> 连接断开,等待重新连接\n"));
                    io.close();
                    socket.close();
                }
            }
        } catch (IOException ex) {
           // ex.printStackTrace();
        }
    }
   
    /**
     * 关闭服务器
     */
    @Override
    public void closeServer(){
        isRunning=false;
        try {
            if(io !=null)
                io.close();
            if(serverSocket !=null)
                serverSocket.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
